from rest_framework import generics, permissions
from rest_framework.response import Response
from django.utils import timezone
from datetime import timedelta
from apps.chefs.models import DjChef
from apps.orders.models import Order, DjChefOrder
from .serializers import ChefAnalyticsSerializer

class ChefAnalyticsView(generics.RetrieveAPIView):
    """
    获取厨师分析数据
    GET /api/chefs/analytics/
    """
    serializer_class = ChefAnalyticsSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_object(self):
        chef = self.request.user.djchef
        
        # 计算今日收入
        today = timezone.now().date()
        today_orders = DjChefOrder.objects.filter(
            chef=chef,
            service_date=today,
            status='completed'
        )
        today_income = sum(order.total_amount for order in today_orders)
        
        # 计算预估收入 (未来7天已确认订单)
        future_orders = DjChefOrder.objects.filter(
            chef=chef,
            service_date__range=[today, today + timedelta(days=7)],
            status__in=['confirmed', 'serving']
        )
        estimated_income = sum(order.total_amount for order in future_orders)
        
        # 统计完成订单数和评分
        completed_orders = DjChefOrder.objects.filter(
            chef=chef,
            status='completed'
        ).count()
        
        rating = chef.profile.average_rating if hasattr(chef, 'profile') else 0
        
        # 计算回头客数量
        repeat_customers = Order.objects.filter(
            chef=chef,
            status='completed'
        ).values('customer').distinct().count()
        
        return {
            'today_income': today_income,
            'estimated_income': estimated_income,
            'completed_orders': completed_orders,
            'rating': rating,
            'repeat_customers': repeat_customers,
            'available_slots': self.calculate_available_slots(chef)
        }
    
    def calculate_available_slots(self, chef):
        # 计算未来7天可用档期数量
        available_slots = 0
        today = timezone.now().date()
        
        for day in range(7):
            current_date = today + timedelta(days=day)
            
            # 检查午餐档期
            lunch_available = not DjChefOrder.objects.filter(
                chef=chef,
                service_date=current_date,
                service_time__hour__gte=11,
                service_time__hour__lt=14,
                status__in=['confirmed', 'serving']
            ).exists()
            
            # 检查晚餐档期
            dinner_available = not DjChefOrder.objects.filter(
                chef=chef,
                service_date=current_date,
                service_time__hour__gte=17,
                service_time__hour__lt=21,
                status__in=['confirmed', 'serving']
            ).exists()
            
            available_slots += lunch_available + dinner_available
        
        return available_slots